let querystring = require('querystring');
var express = require('express');
var router = express.Router();
let path = require('path');
let ini = require('ini');
let fs = require('fs');
/* 初始化 */
let config = ini.decode(fs.readFileSync('config.ini','utf-8'))
let configNumber = 0
for(let a in config.phone) configNumber++;
/* GET home page. */
router.get('/', (req, res, next)=>{
  res.render('index', {
    title: '欢迎使用统计系统',
    allpeople : configNumber
  });
});
router.get('/ping', (req, res, next)=>{
  res.send('pong');
});
router.post('/ping',(req, res, next)=>{
  res.send({code:"1",data:'pong'})
})

// push
function g(a){
  return `${a<10?"0":""}${a}`
}
function getTime(asdf){
  let d = new Date();
  if(d.getHours() < 4){
    d=new Date(d.getTime()-require('ms')('6 hours'))
  }
  if(asdf)return d;
  else return `${d.getFullYear()}-${g(d.getMonth()+1)}-${g(d.getDate())}`
}

router.get('/push', function(req, res, next) {
  res.render('push', { title: '统计系统',d:getTime('asdf')});
});

router.post('/push',function(req, res, next){
  console.log(req.body)
  let temp = req.body;
  if(temp.id&&temp.a&&temp.b&&temp.address){
    // 使用|分割两个手机号
    let phonePass = false,phoneid
    if(/\|/.test(config.phone[temp.id])){
      config.phone[temp.id].split("|").forEach((a,i)=>{
        if(!phonePass){
          phonePass = (`${temp.a}****${temp.b}` == a)
          phoneid=i+1
        }
      })
    }else{
      phonePass = (`${temp.a}****${temp.b}`== config.phone[temp.id])
    }
    if(phonePass){
      let phone = `${temp.a}|${temp.b}`
      fs.writeFileSync(path.resolve(`data/${getTime()}.txt`),`uid=${encodeURI(temp.id)}&phone=${encodeURI(phone)}&address=${encodeURI(temp.address)}&time=${temp.time}\n`,{flag:'a'})
      if(phoneid)console.log(`${temp.id} User Phone Number : ${phoneid}`)
      res.send({code:0,msg:`成功，手机号序号：${phoneid||1}`})
    }else{
      res.send({code:2,msg:"失败，唯一标识(姓名)与手机号不符"})
    }
  }else{
    res.send({code:1,msg:"失败，缺少数据"})
  }
});

// get
router.get('/get',(req, res, next)=>{
  let date = req.body.date||getTime(),data,code=200
  let token = config.phone,list={}
  let output = ["",""]
  for (const key in token) list[key]=0
  try {
    data = fs.readFileSync(path.resolve('data/'+date+'.txt'),'utf-8');
    data = data.split('\n').map(a=>a=querystring.parse(a))
    data.pop()
    data.forEach(a=>{
      list[a.uid]=1
    })
  }catch(d){
    code = 404
  }
  for (const key in list){
    let isPushed = list[key]
    output[isPushed?1:0] +=`<li>${key}${isPushed?"已":"未"}提交</li>`
  }
  res.render('selectView', {title: '统计系统 - 查询',html:output});
})
router.post('/get',(req, res, next)=>{
  try {
    let date = req.body.date||getTime();
    let data = fs.readFileSync(path.resolve('data/'+date+'.txt'),'utf-8');
    data = data.split('\n').map(a=>a=querystring.parse(a))
    if(!req.body.token)data = data.map(a=>{let item = a;delete item.time;return item})
    if(!data[data.length-1].id)data.pop()
    res.send({code:0,data:data,date:date})
  } catch (d) {
    res.status(404).send({code:404,data:[],date:req.body.date})
  }
})

module.exports = router;
